<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" tppabs="http://res.layui.com/layui/dist/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="batchDel">批量删除</button><!-- 88行实现方法 -->
        <button class="layui-btn layui-btn-sm" lay-event="writeExcel">导出Excel</button><!-- 111行实现方法 -->
        <button class="layui-btn layui-btn-sm" lay-event="getExcelTemplate">获取Excel模板</button><!-- 126行实现方法 -->
        <!-- 330行实现方法 -->
        <button type="button" class="layui-btn" id="test1">
            <i class="layui-icon">&#xe67c;</i>导入Excel
        </button>

    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a><!-- 162行 实现编辑方法-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>

<script>
    layui.use('table', function(){
        var table = layui.table;

        table.render({
            elem: '#test'
            ,url:'/user/findByPage'/*tpa=https://www.layuiweb.com/test/table/demo1.json*/
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,title: '用户数据表'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'ID', width:100, fixed: 'left', sort: true}
                ,{field:'userName', title:'用户名', width:100}
                ,{field:'userPwd', title:'密码', width:100}
                ,{field:'userRealname', title:'真实名称', width:100}
                ,{field:'userGender', title:'性别', width:100}
                ,{field:'userEmail', title:'邮箱', width:100}
                ,{field:'userId', title:'身份证', width:100}
                ,{field:'userBirthdate', title:'生日', width:100,
                    templet:"<div>{{ layui.util.toDateString(d.userBirthdate,'yyyy-MM-dd') }}</div>"
                 }
                ,{field:'userLock', title:'锁定状态', width:100}
                ,{field:'userAddress', title:'地址', width:100}
                ,{field:'userImage', title:'头像', width:100,
                    templet:"<div><img src='{{ d.userImage }}' width='50' height='50'></div>"
                 }

                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
            ]]
            //,page: true
            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                ,curr: 1 //设定初始在第 1 页
                ,groups: 3 //只显示 3 个连续页码
                ,first: "首页" //不显示首页
                ,last: "尾页" //不显示尾页
                ,limit:3
                ,limits:[3,7,10]

            }
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'batchDel':
                    var data = checkStatus.data;
                    //layer.alert(JSON.stringify(data));
                    //获取选中数据的id
                    var ids = "";
                    //遍历
                    for(let i = 0; i < data.length; i++){
                        ids += "&ids=" + data[i].id;
                    }
                    alert("批量删除的ids：" + ids)

                    //发送ajax，调用后台接口
                    $.get("/user/deleteByIds", ids,
                        function(data){
                            if("success" == data){
                                table.reload("test",{});//重载当前表格
                            }
                    });

                    break;
                case 'writeExcel':<!-- 实现方法导出Excel -->
                    var data = checkStatus.data;
                    //layer.msg('选中了：'+ data.length + ' 个');

                    //获取选中数据的id
                    var ids = "";
                    //遍历
                    for(let i = 0; i < data.length; i++){
                        ids += "&ids=" + data[i].id;
                    }
                    alert("要查询的ids：" + ids)

                    location.href = "/user/findByIds?ids="+ids;

                    break;
                case 'getExcelTemplate':
                    //layer.msg(checkStatus.isAll ? '全选': '未全选');

                    location.href = "/excel/user.xlsx"

                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();//删除结构，没有调用后台接口
                    layer.close(index);

                    //获取id，删除
                    var deleteId = data.id;

                    //发送ajax，调用后台接口
                    $.get("/user/deleteById", { "id": deleteId },
                        function(data){
                            if("success" == data){
                                table.reload("test",{});//重载当前表格
                            }
                    });

            // 编辑方法
                });
            } else if(obj.event === 'edit'){
                // layer.prompt({
                //     formType: 2
                //     ,value: data.email
                // }, function(value, index){
                //     obj.update({
                //         email: value
                //     });
                //     layer.close(index);
                // });

                //编辑之前需要查询单个
                //layer.alert(JSON.stringify(data));
                findById(data);
            }
        });
    });
</script>
</body>

<script>

    function findById(data) {
        //弹框
        layer.open({
            type: 1,
            content: $("#updateForm").html(),
            title: ['修改页面', 'font-size:18px;'],
            area: ['600px', '600px'],

            //弹出后回调
            success: function(){
                $("#id").val(data.id);
                $("#userName").val(data.userName);
                $("#userPwd").val(data.userPwd);
                $("#userRealname").val(data.userRealname);

                if('男' == data.userGender){
                    $("#userGender").append("<input type='radio' name='userGender' value='男' checked />"+'男'+"<input type='radio' name='userGender' value='女'/>"+'女'+"")
                }else{
                    $("#userGender").append("<input type='radio' name='userGender' value='男' />"+'男'+"<input type='radio' name='userGender' value='女' checked />"+'女'+"")
                }

                $("#userEmail").val(data.userEmail);
                $("#userPhone").val(data.userPhone);
                $("#userId").val(data.userId);
                $("#userBirthdate").val(layui.util.toDateString(data.userBirthdate,'yyyy-MM-dd'));

                if("0" == data.userLock){
                    $("#userLock").append("<option value='0' selected>"+'解锁'+"</option> <option value='1'>"+'锁定'+"</option>");
                }else{
                    $("#userLock").append("<option value='0' >"+'解锁'+"</option> <option value='1' selected>"+'锁定'+"</option>");
                }

                $("#userAddress").val(data.userAddress);

                //渲染页面
                layui.form.render();
            },

            btn: ['提交', '取消']
            ,yes: function(index, layero){
                alert("-----")

                //修改操作
                $.get("/user/updateUser", $("#updateUser").serialize(),
                    function(data){
                        if("success" == data){
                            location.reload();//刷新当前页面
                        }
                    });

            }
            ,btn2: function(index, layero){
                alert("取消")
            }
        });


    }

</script>

<script type="text/html" id="updateForm">

    <form class="layui-form" id="updateUser">

        <!-- 把id 作为隐藏域传过去 -->
        <input type="hidden" name="id" id="id">

        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="userName" id="userName" required  lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码框</label>
            <div class="layui-input-inline">
                <input type="password" name="userPwd" id="userPwd" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">密码必须以字母开头</div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" name="userRealname" id="userRealname" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block" id="userGender">


            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="userEmail" id="userEmail" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-block">
                <input type="text" name="userPhone" id="userPhone" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">身份证号</label>
            <div class="layui-input-block">
                <input type="text" name="userId" id="userId" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">日期</label>
                <div class="layui-input-inline">
                    <input type="date" name="userBirthdate" id="userBirthdate" class="layui-input" id="userBirthdate" placeholder="yyyy-MM-dd">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">是否锁定</label>
            <div class="layui-input-block">
                <select name="userLock" id="userLock" lay-verify="required">

                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <input type="text" name="userAddress" id="userAddress" class="layui-input">
            </div>
        </div>

    </form>

</script>
<!-- 导入Excel -->
<script>
    layui.use('upload', function(){
        var upload = layui.upload;

        //执行实例
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            ,accept: 'file'
            ,url: '/user/readExcel' //上传接口
            ,done: function(res){
                if("success" == res.msg){
                    alert("导入数据成功");
                    location.reload();
                }
            }
            ,error: function(){
                //请求异常回调
                alert("导入数据失败")
            }
        });
    });
</script>

</html>